<template>
  <div class="service-booking-page">
    <div class="container">
      <!-- 页面头部 -->
      <div class="page-header">
        <el-button @click="handleBack" :icon="ArrowLeft" circle />
        <h1>预订服务</h1>
        <div class="placeholder"></div>
      </div>

      <!-- 服务信息 -->
      <el-card class="service-info-card">
        <div class="service-content">
          <div class="service-image">
            <el-image
              :src="serviceInfo.image || '/default-service.jpg'"
              fit="cover"
              class="image"
            />
          </div>
          <div class="service-details">
            <h3>{{ serviceInfo.name }}</h3>
            <p class="description">{{ serviceInfo.description }}</p>
            <div class="merchant-info">
              <span class="merchant-name">{{ merchantInfo.name }}</span>
              <el-rate v-model="merchantInfo.rating" disabled size="small" />
            </div>
            <div class="price-info">
              <span class="price">¥{{ serviceInfo.price }}</span>
              <span class="unit">/ {{ serviceInfo.unit || '次' }}</span>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 预订表单 -->
      <el-form 
        :model="bookingForm" 
        :rules="bookingRules" 
        ref="formRef" 
        label-width="100px"
        class="booking-form"
      >
        <!-- 服务地址 -->
        <el-card class="form-section">
          <template #header>
            <h3>服务地址</h3>
          </template>
          
          <el-form-item prop="addressId">
            <div class="address-selector">
              <div 
                v-if="selectedAddress" 
                class="selected-address"
                @click="showAddressDialog = true"
              >
                <div class="address-header">
                  <el-icon><Location /></el-icon>
                  <span class="address-label">{{ selectedAddress.label }}</span>
                  <el-tag v-if="selectedAddress.isDefault" size="small" type="primary">默认</el-tag>
                </div>
                <div class="address-detail">{{ selectedAddress.fullAddress }}</div>
                <div class="contact-info">
                  {{ selectedAddress.contactName }} {{ selectedAddress.contactPhone }}
                </div>
              </div>
              
              <el-button 
                v-else
                @click="showAddressDialog = true"
                type="primary"
                :icon="Plus"
                class="add-address-btn"
              >
                选择服务地址
              </el-button>
            </div>
          </el-form-item>
        </el-card>

        <!-- 服务时间 -->
        <el-card class="form-section">
          <template #header>
            <h3>服务时间</h3>
          </template>
          
          <el-form-item label="预约日期" prop="appointmentDate">
            <el-date-picker
              v-model="bookingForm.appointmentDate"
              type="date"
              placeholder="选择日期"
              :disabled-date="disabledDate"
              size="large"
              style="width: 100%"
            />
          </el-form-item>
          
          <el-form-item label="预约时间" prop="appointmentTime">
            <div class="time-slots">
              <div
                v-for="slot in availableTimeSlots"
                :key="slot.value"
                class="time-slot"
                :class="{ 
                  'selected': bookingForm.appointmentTime === slot.value,
                  'disabled': slot.disabled 
                }"
                @click="selectTimeSlot(slot)"
              >
                {{ slot.label }}
              </div>
            </div>
          </el-form-item>
        </el-card>

        <!-- 服务数量 -->
        <el-card class="form-section">
          <template #header>
            <h3>服务数量</h3>
          </template>
          
          <el-form-item label="数量" prop="quantity">
            <el-input-number
              v-model="bookingForm.quantity"
              :min="1"
              :max="10"
              size="large"
              @change="calculateTotalAmount"
            />
            <span class="quantity-unit">{{ serviceInfo.unit || '次' }}</span>
          </el-form-item>
        </el-card>

        <!-- 优惠券 -->
        <el-card class="form-section">
          <template #header>
            <h3>优惠券</h3>
          </template>
          
          <el-form-item>
            <div class="coupon-selector" @click="showCouponDialog = true">
              <div v-if="selectedCoupon" class="selected-coupon">
                <el-icon><Ticket /></el-icon>
                <div class="coupon-info">
                  <div class="coupon-name">{{ selectedCoupon.name }}</div>
                  <div class="coupon-desc">立减¥{{ selectedCoupon.amount }}</div>
                </div>
                <div class="coupon-amount">-¥{{ selectedCoupon.amount }}</div>
              </div>
              <div v-else class="no-coupon">
                <el-icon><Ticket /></el-icon>
                <span>选择优惠券</span>
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>
          </el-form-item>
        </el-card>

        <!-- 备注信息 -->
        <el-card class="form-section">
          <template #header>
            <h3>备注信息</h3>
          </template>
          
          <el-form-item>
            <el-input
              v-model="bookingForm.note"
              type="textarea"
              :rows="3"
              placeholder="请输入特殊要求或备注信息（选填）"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-card>
      </el-form>

      <!-- 价格明细 -->
      <el-card class="price-summary-card">
        <h3>价格明细</h3>
        <div class="price-details">
          <div class="price-item">
            <span>服务费用</span>
            <span>¥{{ serviceAmount }}</span>
          </div>
          <div class="price-item" v-if="selectedCoupon">
            <span>优惠券</span>
            <span class="discount">-¥{{ selectedCoupon.amount }}</span>
          </div>
          <div class="price-item total">
            <span>总计</span>
            <span class="total-amount">¥{{ totalAmount }}</span>
          </div>
        </div>
      </el-card>

      <!-- 提交按钮 -->
      <div class="submit-section">
        <el-button
          type="primary"
          size="large"
          :loading="submitting"
          @click="handleSubmit"
          class="submit-btn"
          :disabled="!isFormValid"
        >
          确认预订
        </el-button>
      </div>
    </div>

    <!-- 地址选择对话框 -->
    <el-dialog v-model="showAddressDialog" title="选择地址" width="600px">
      <div class="address-list">
        <div
          v-for="address in addressList"
          :key="address.id"
          class="address-item"
          :class="{ 'selected': selectedAddress?.id === address.id }"
          @click="selectAddress(address)"
        >
          <div class="address-header">
            <span class="address-label">{{ address.label }}</span>
            <el-tag v-if="address.isDefault" size="small" type="primary">默认</el-tag>
          </div>
          <div class="address-detail">{{ address.fullAddress }}</div>
          <div class="contact-info">
            {{ address.contactName }} {{ address.contactPhone }}
          </div>
        </div>
        
        <div class="add-new-address" @click="addNewAddress">
          <el-icon><Plus /></el-icon>
          <span>添加新地址</span>
        </div>
      </div>
    </el-dialog>

    <!-- 优惠券选择对话框 -->
    <el-dialog v-model="showCouponDialog" title="选择优惠券" width="600px">
      <div class="coupon-list">
        <div
          v-for="coupon in availableCoupons"
          :key="coupon.id"
          class="coupon-item"
          :class="{ 
            'selected': selectedCoupon?.id === coupon.id,
            'disabled': !coupon.available 
          }"
          @click="selectCoupon(coupon)"
        >
          <div class="coupon-content">
            <div class="coupon-amount">¥{{ coupon.amount }}</div>
            <div class="coupon-info">
              <div class="coupon-name">{{ coupon.name }}</div>
              <div class="coupon-condition">{{ coupon.condition }}</div>
              <div class="coupon-expire">有效期至 {{ formatDate(coupon.expireTime) }}</div>
            </div>
          </div>
          <div class="coupon-status">
            <el-radio :value="selectedCoupon?.id === coupon.id" :disabled="!coupon.available" />
          </div>
        </div>
        
        <div v-if="availableCoupons.length === 0" class="no-coupon-tip">
          <el-empty description="暂无可用优惠券" />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showCouponDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmCouponSelection">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  Location,
  Plus,
  Ticket,
  ArrowRight
} from '@element-plus/icons-vue'
import { serviceApi, addressApi, couponApi, orderApi } from '@/services/api'
import { useUserStore } from '@/stores/user'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 数据定义
const formRef = ref()
const loading = ref(true)
const submitting = ref(false)
const showAddressDialog = ref(false)
const showCouponDialog = ref(false)

const serviceInfo = ref({})
const merchantInfo = ref({})
const addressList = ref([])
const availableCoupons = ref([])
const selectedAddress = ref(null)
const selectedCoupon = ref(null)

const bookingForm = reactive({
  serviceId: '',
  merchantId: '',
  addressId: '',
  appointmentDate: '',
  appointmentTime: '',
  quantity: 1,
  note: ''
})

// 可用时间段
const availableTimeSlots = ref([
  { label: '09:00-10:00', value: '09:00', disabled: false },
  { label: '10:00-11:00', value: '10:00', disabled: false },
  { label: '11:00-12:00', value: '11:00', disabled: false },
  { label: '14:00-15:00', value: '14:00', disabled: false },
  { label: '15:00-16:00', value: '15:00', disabled: false },
  { label: '16:00-17:00', value: '16:00', disabled: false },
  { label: '17:00-18:00', value: '17:00', disabled: false },
  { label: '18:00-19:00', value: '18:00', disabled: false }
])

// 表单验证规则
const bookingRules = {
  addressId: [
    { required: true, message: '请选择服务地址', trigger: 'change' }
  ],
  appointmentDate: [
    { required: true, message: '请选择预约日期', trigger: 'change' }
  ],
  appointmentTime: [
    { required: true, message: '请选择预约时间', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: '请选择服务数量', trigger: 'change' }
  ]
}

// 计算属性
const serviceAmount = computed(() => {
  return (serviceInfo.value.price || 0) * bookingForm.quantity
})

const totalAmount = computed(() => {
  let amount = serviceAmount.value
  if (selectedCoupon.value) {
    amount -= selectedCoupon.value.amount
  }
  return Math.max(amount, 0)
})

const isFormValid = computed(() => {
  return selectedAddress.value && 
         bookingForm.appointmentDate && 
         bookingForm.appointmentTime && 
         bookingForm.quantity > 0
})

// 生命周期
onMounted(() => {
  const serviceId = route.params.serviceId || route.query.serviceId
  const merchantId = route.query.merchantId
  
  if (serviceId) {
    bookingForm.serviceId = serviceId
    fetchServiceInfo(serviceId)
  }
  
  if (merchantId) {
    bookingForm.merchantId = merchantId
    fetchMerchantInfo(merchantId)
  }
  
  fetchAddressList()
  fetchAvailableCoupons()
})

// 方法定义
const fetchServiceInfo = async (serviceId) => {
  try {
    const response = await serviceApi.getServiceDetail(serviceId)
    serviceInfo.value = response.data
  } catch (error) {
    console.error('获取服务信息失败:', error)
    // 使用模拟数据
    serviceInfo.value = {
      id: serviceId,
      name: '专业洗衣服务',
      description: '专业的洗衣护理服务，采用进口设备和环保洗涤剂',
      price: 25,
      unit: '件',
      image: '/default-service.jpg'
    }
  }
}

const fetchMerchantInfo = async (merchantId) => {
  try {
    const response = await serviceApi.getMerchantInfo(merchantId)
    merchantInfo.value = response.data
  } catch (error) {
    console.error('获取商家信息失败:', error)
    // 使用模拟数据
    merchantInfo.value = {
      id: merchantId,
      name: '专业洗护店',
      rating: 4.8
    }
  }
}

const fetchAddressList = async () => {
  try {
    const response = await addressApi.getAddressList()
    addressList.value = response.data
    
    // 默认选择第一个地址
    if (addressList.value.length > 0) {
      const defaultAddress = addressList.value.find(addr => addr.isDefault) || addressList.value[0]
      selectedAddress.value = defaultAddress
      bookingForm.addressId = defaultAddress.id
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    // 使用模拟数据
    addressList.value = [
      {
        id: 1,
        label: '家',
        fullAddress: '北京市朝阳区三里屯SOHO 1号楼1001室',
        contactName: '张三',
        contactPhone: '138****1234',
        isDefault: true
      }
    ]
    selectedAddress.value = addressList.value[0]
    bookingForm.addressId = addressList.value[0].id
  }
}

const fetchAvailableCoupons = async () => {
  try {
    const response = await couponApi.getAvailableCoupons({
      merchantId: bookingForm.merchantId,
      serviceId: bookingForm.serviceId,
      amount: serviceAmount.value
    })
    availableCoupons.value = response.data.map(coupon => ({
      ...coupon,
      available: coupon.minAmount <= serviceAmount.value
    }))
  } catch (error) {
    console.error('获取优惠券失败:', error)
    // 使用模拟数据
    availableCoupons.value = [
      {
        id: 1,
        name: '新用户专享',
        amount: 5,
        condition: '满20元可用',
        expireTime: '2024-12-31',
        minAmount: 20,
        available: true
      }
    ]
  }
}

const disabledDate = (time) => {
  // 禁用今天之前的日期
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

const selectTimeSlot = (slot) => {
  if (slot.disabled) return
  bookingForm.appointmentTime = slot.value
}

const calculateTotalAmount = () => {
  // 重新计算优惠券可用性
  availableCoupons.value.forEach(coupon => {
    coupon.available = coupon.minAmount <= serviceAmount.value
  })
  
  // 如果当前选择的优惠券不可用，则取消选择
  if (selectedCoupon.value && !selectedCoupon.value.available) {
    selectedCoupon.value = null
  }
}

const selectAddress = (address) => {
  selectedAddress.value = address
  bookingForm.addressId = address.id
  showAddressDialog.value = false
}

const addNewAddress = () => {
  showAddressDialog.value = false
  router.push('/addresses/add?redirect=' + encodeURIComponent(route.fullPath))
}

const selectCoupon = (coupon) => {
  if (!coupon.available) return
  selectedCoupon.value = coupon
}

const confirmCouponSelection = () => {
  showCouponDialog.value = false
}

const handleBack = () => {
  router.back()
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    await ElMessageBox.confirm(
      '确认提交订单吗？提交后将跳转到支付页面',
      '确认预订',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    submitting.value = true
    
    const orderData = {
      serviceId: bookingForm.serviceId,
      merchantId: bookingForm.merchantId,
      addressId: bookingForm.addressId,
      appointmentDate: bookingForm.appointmentDate,
      appointmentTime: bookingForm.appointmentTime,
      quantity: bookingForm.quantity,
      note: bookingForm.note,
      couponId: selectedCoupon.value?.id,
      serviceAmount: serviceAmount.value,
      couponAmount: selectedCoupon.value?.amount || 0,
      totalAmount: totalAmount.value
    }
    
    const response = await orderApi.createOrder(orderData)
    
    ElMessage.success('订单创建成功！')
    
    // 跳转到支付页面
    router.push(`/payment/${response.data.orderId}`)
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('创建订单失败:', error)
      ElMessage.error('创建订单失败，请重试')
    }
  } finally {
    submitting.value = false
  }
}

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}
</script>

<style lang="scss" scoped>
.service-booking-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h1 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
  }

  .placeholder {
    width: 32px;
  }
}

.el-card {
  margin-bottom: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.service-info-card {
  .service-content {
    display: flex;
    gap: 16px;
  }

  .service-image {
    width: 80px;
    height: 80px;
    border-radius: 8px;
    overflow: hidden;
    flex-shrink: 0;

    .image {
      width: 100%;
      height: 100%;
    }
  }

  .service-details {
    flex: 1;

    h3 {
      margin: 0 0 8px 0;
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }

    .description {
      margin: 0 0 12px 0;
      color: #666;
      font-size: 14px;
      line-height: 1.4;
    }

    .merchant-info {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 12px;

      .merchant-name {
        font-size: 14px;
        color: #666;
      }
    }

    .price-info {
      display: flex;
      align-items: baseline;
      gap: 4px;

      .price {
        font-size: 20px;
        font-weight: 600;
        color: #e6a23c;
      }

      .unit {
        font-size: 14px;
        color: #999;
      }
    }
  }
}

.form-section {
  .el-card__header {
    padding: 16px 20px;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
  }

  .el-card__body {
    padding: 20px;
  }
}

.address-selector {
  .selected-address {
    border: 1px solid #dcdfe6;
    border-radius: 8px;
    padding: 16px;
    cursor: pointer;
    transition: border-color 0.3s ease;

    &:hover {
      border-color: #409eff;
    }

    .address-header {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 8px;

      .address-label {
        font-weight: 500;
        color: #333;
      }
    }

    .address-detail {
      color: #666;
      margin-bottom: 8px;
    }

    .contact-info {
      color: #999;
      font-size: 14px;
    }
  }

  .add-address-btn {
    width: 100%;
    height: 80px;
    border-style: dashed;
  }
}

.time-slots {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 12px;
}

.time-slot {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 12px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover:not(.disabled) {
    border-color: #409eff;
    color: #409eff;
  }

  &.selected {
    border-color: #409eff;
    background-color: #ecf5ff;
    color: #409eff;
  }

  &.disabled {
    background-color: #f5f7fa;
    color: #c0c4cc;
    cursor: not-allowed;
  }
}

.quantity-unit {
  margin-left: 8px;
  color: #666;
}

.coupon-selector {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: border-color 0.3s ease;

  &:hover {
    border-color: #409eff;
  }

  .selected-coupon {
    display: flex;
    align-items: center;
    gap: 12px;

    .coupon-info {
      flex: 1;

      .coupon-name {
        font-weight: 500;
        color: #333;
        margin-bottom: 4px;
      }

      .coupon-desc {
        color: #666;
        font-size: 14px;
      }
    }

    .coupon-amount {
      color: #e6a23c;
      font-weight: 600;
    }
  }

  .no-coupon {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #666;
  }
}

.price-summary-card {
  h3 {
    margin: 0 0 16px 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }

  .price-details {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .price-item {
    display: flex;
    justify-content: space-between;
    align-items: center;

    &.total {
      padding-top: 12px;
      border-top: 1px solid #f0f0f0;
      font-weight: 600;

      .total-amount {
        font-size: 18px;
        color: #e6a23c;
      }
    }
  }

  .discount {
    color: #67c23a;
  }
}

.submit-section {
  margin-top: 24px;
  margin-bottom: 40px;

  .submit-btn {
    width: 100%;
    height: 48px;
    font-size: 16px;
    font-weight: 500;
  }
}

// 对话框样式
.address-list {
  max-height: 400px;
  overflow-y: auto;
}

.address-item {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    border-color: #409eff;
  }

  &.selected {
    border-color: #409eff;
    background-color: #ecf5ff;
  }

  .address-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;

    .address-label {
      font-weight: 500;
      color: #333;
    }
  }

  .address-detail {
    color: #666;
    margin-bottom: 8px;
  }

  .contact-info {
    color: #999;
    font-size: 14px;
  }
}

.add-new-address {
  border: 1px dashed #dcdfe6;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  color: #409eff;
  transition: border-color 0.3s ease;

  &:hover {
    border-color: #409eff;
  }

  span {
    margin-left: 8px;
  }
}

.coupon-list {
  max-height: 400px;
  overflow-y: auto;
}

.coupon-item {
  display: flex;
  align-items: center;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  margin-bottom: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover:not(.disabled) {
    border-color: #409eff;
  }

  &.selected {
    border-color: #409eff;
    background-color: #ecf5ff;
  }

  &.disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  .coupon-content {
    display: flex;
    flex: 1;
    padding: 16px;

    .coupon-amount {
      width: 60px;
      font-size: 18px;
      font-weight: 600;
      color: #e6a23c;
      text-align: center;
      margin-right: 16px;
    }

    .coupon-info {
      flex: 1;

      .coupon-name {
        font-weight: 500;
        color: #333;
        margin-bottom: 4px;
      }

      .coupon-condition {
        color: #666;
        font-size: 14px;
        margin-bottom: 4px;
      }

      .coupon-expire {
        color: #999;
        font-size: 12px;
      }
    }
  }

  .coupon-status {
    padding: 16px;
  }
}

.no-coupon-tip {
  text-align: center;
  padding: 40px 20px;
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .service-info-card .service-content {
    flex-direction: column;
  }

  .service-image {
    align-self: center;
  }

  .time-slots {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style> 